package com.schedule.task.controller;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.web.bind.annotation.RestController;


@Slf4j
@RestController
public class TestController {

    private final SimpMessagingTemplate simpMessagingTemplate;

    private StringRedisTemplate stringRedisTemplate;


    @Autowired
    public TestController(SimpMessagingTemplate simpMessagingTemplate, StringRedisTemplate stringRedisTemplate) {
        this.simpMessagingTemplate = simpMessagingTemplate;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    // 测试客户端主动发消息给服务端
    @MessageMapping("/message/test")
    public String receiveMessage(SimpMessageHeaderAccessor sha, Book book) {

         //log.info("receive message principal name: {}", principal.getName());
        log.info("这是客户端发过来的数据： {}", JSON.toJSONString(book));
        // 测试：服务端主动发给客户端之广播消息。也可以用 @SendTo("/topic/message") 注解
        simpMessagingTemplate.convertAndSend("/topic/message", "这是一条服务端向你广播的消息111");
        // 测试：服务端主动发给客户端之一对一消息。也可以用 @SendToUser("/topic/message/test") 注解
        String sessionId = this.stringRedisTemplate.opsForValue().get("UserId-"+ book.getId());
        System.out.println(sessionId);
        simpMessagingTemplate.convertAndSendToUser(sessionId, "/topic/message/test", "这是一条服务端向你单独发送的消息222");
        // 测试：向客户端的默认路径发送消息默认。默认路径的规则为 "/topic/" + @MessageMapping中的路径，所以这里的路径就是：/topic/message/test
        // 根据规则，客户端通过 subscribe 这个路径 /topic/message/test 可以收到return的消息
        return "这条是服务端接受到请求后，走默认路径给你返回的消息333. receiveMessage";
    }


    // 测试客户端主动发订阅给服务端
    @SubscribeMapping("/subscribe/test")
    public String receiveSubscribe() {
        log.info("receive subscriber principal name: {}");
        // 根据规则，客户端通过 subscribe 这个路径 /topic/subscribe/test 可以收到return的消息
        return "这条是服务端接受到请求后，走默认路径给你返回的消息444. receiveSubscribe";
    }

    public static class Book {
        private Integer id;
        private String title;
        private String color;

        public Integer getId() {
            return id;
        }


        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getColor() {
            return color;
        }

        public void setColor(String color) {
            this.color = color;
        }
    }

}
